<?php
namespace app\models;

use Yii;
use app\models\BaseModel;
use app\dao\ClientDAO;
use app\dao\SaleOutSyncDAO;
use app\dao\SaleOutSyncDetailDAO;
use app\dao\ProductDAO;
use app\enum\EnumOther;
use app\enum\EnumOriginType;
				 
class SaleOutSyncModel extends BaseModel
{
 	/**
 	 * @desc 覆盖父方法返回对象
 	 * @author liaojianwen
 	 * @date 2017-02-07
 	 * @return SaleModel
 	 */
 	public static function model($className=__CLASS__)
 	{
 		return parent::model($className);
 	}
 	
 	/**
 	 * @desc 店铺生成要货单
 	 * @author lizichuan
 	 * @date 2018-02-26
 	 */
 	public function storeInsertSaleOut($productInfo)
 	{
 		if(!$productInfo){
 			return false;
 		}
 		$tr = Yii::$app->db->beginTransaction();
 		try {
	 		$saleout_no = EnumOriginType::SALE_OUT.date('YmdHis');
	 		$saleout_type = EnumOriginType::origin_sale_out_market;
	 		$warehouse_id = EnumOther::DEFAULT_WARE;
	 		$client = ClientDAO::getInstance()->iselect("client_id", "store_id=:sid and delete_flag=:flag", [':sid'=>$productInfo['head']['store_id'],':flag'=> EnumOther::NO_DELETE],'one');
			if(empty($client)){
				$tr->rollBack();
				return false;
			}
	 		$saleout_head = [
	 			'saleout_no'=>$saleout_no,
	 			'saleout_date'=> $productInfo['head']['saleout_date'],
	 			'saleout_type'=>$saleout_type,
	 			'warehouse_id' => $warehouse_id,
	 			'customer_id'=> $client['client_id'],
	//  			'handle_man'=> ,//
	 			'create_man'=> '1',//admin
	 			'create_time'=> $productInfo['head']['saleout_date'],
	 			'remark' => $productInfo['head']['remark'],
	 			'saleout_amount' => $productInfo['head']['saleout_amount'],
	 			'total_discount' => $productInfo['head']['total_discount'],
	 			'total_amount' => $productInfo['head']['total_amount'],
	 			'discount_amount' => $productInfo['head']['discount_amount'],
	 		];
	 		$res_head = SaleOutSyncDAO::getInstance()->iinsert($saleout_head,true);
	 		if(!$res_head){
	 			$tr->rollBack();
	 			return false;
	 		} else {
		 		foreach ($productInfo['detail'] as $det){
		 			$product = ProductDAO::getInstance()->iselect(['quantity_unit'], "product_id =:pid", [':pid'=>$det['product_id']], 'one');
		 			$saleout_det = [
		 				'saleout_id'=> $res_head,
		 				'product_id'=> $det['product_id'],
		 				'quantity'=> $det['quantity'],
		 				'quantity_unit' => $product['quantity_unit'],
		 				'price'=> $det['price'],//供货价
		 				'amount' => $det['quantity'] * $det['price'],
		 				'base_quantity'=> $det['base_quantity'],
		 				'base_unit' => $product['quantity_unit'],
		 				'minus_quantity' => $det['base_quantity'],
		 				'create_time' => $productInfo['head']['saleout_date'],
		 			];
		 			$res_det = SaleOutSyncDetailDAO::getInstance()->iinsert($saleout_det, true);
		 			if(!$res_det){
		 				$tr->rollBack();
		 				return  false;
		 			}
		 		}
		 	}
			$tr->commit();
			return true;
	 	}
		catch (\Exception $e)
		{
	 		$tr->rollBack();
	 		return false;
	 	}
 	}
}
